/**
 * 模态框
 */
module.exports = function($scope, $modalInstance, $resource, toaster, item, center_list){

    //查询接口已绑定的其他接口
    function init() {
        $scope.title = item;
        $scope.center_list = center_list.slice(1);
        $scope.searchfrom = {};
		$resource('/api/as/sc/sysfun/getBindFunList', {}, {}).save({'id': item.id}, function(res){
			if(res.errcode === 0){
                $scope.sel_list = res.data;
                angular.forEach($scope.sel_list, function(item){
                    item.status = true;
                });
			}else{
				alert(res.errmsg);
			}
		});
    };
    init();

    //切换center时,查询Center内可被绑定的接口列表
    $scope.search = function (){
        var para = {
            'center_code': $scope.searchfrom.center.center_code,
            'type': '1'
        }
        $resource('/api/as/sc/menu/getForMenuList', {}, {}).save(para, function (res) {
            if (res.errcode === 0) {
                $scope.interface_list = res.data;
            } else {
                alert(res.errmsg);
            }
        });
    };

    //选择并添加接口
    $scope.selectApi = function () {
        for(var i = 0; i < $scope.sel_list.length; i++){
            if($scope.searchfrom.api.id == $scope.sel_list[i].bind_function_id){
                return;
            }
        }
        var temp = {
            'id': item.id,
            'bind_function_id': $scope.searchfrom.api.id,
            'status': false,
            'flag': true
        };
        $scope.sel_list.push(temp);
    };

    //编辑已绑定的接口
    $scope.update = function (item) {
        item.status = false;
    };

    //删除已选接口
    $scope.remove = function (index) {
        if(confirm('确认要删除吗？') == true){
            if(!$scope.sel_list[index].flag){
                $resource('/api/as/sc/sysfun/delBindApi', {}, {}).save($scope.sel_list[index], function(res){
                    if(res.errcode !== 0){
                        toaster.error({title: '', body: res.errmsg});
                    }
                });
            }
            $scope.sel_list.splice(index,1);
            toaster.success({title: "", body: '删除成功'});
        }
    };

    //保存
    $scope.save = function (item) {
        $resource('/api/ac/sc/systemFunction/saveBindApi', {}, {}).save(item, function (res) {
            if (res.errcode === 0) {
                item.status = true;
                delete item.flag;   //删除属性
                toaster.success({title: "", body: '保存成功'});
            } else {
                toaster.error({title: '', body: res.errmsg});
            }
        });
    };

    //取消
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };

};